<?php
declare(strict_types=1);

namespace App\Process;

use App\Game\Core\Djs;
use App\Game\Timer\GameTimer;
use Hyperf\Process\AbstractProcess;
use Hyperf\Process\Annotation\Process;

/**
 * @Process(name="djs_timer_process")
 */
class DjsTimerProcess extends AbstractProcess
{

    /**
     * 进程数量
     * @var int
     */
    public $nums = 1;

    /**
     * 进程名称
     * @var string
     */
    public $name = 'djs-timer-process';

    public function handle(): void
    {
        $game_conf = config('game');
        $addkey = $game_conf['djs_timer_add'];
        $delkey = $game_conf['djs_timer_del'];
        $redis = redis();
        while (true) {
            //优先销毁
            $deltask = $redis->rpop($delkey);
            if ($deltask) {
                $timerId = json_decode($deltask, true);
                if ($timerId) {
                    $res = \Swoole\Timer::clear((int)$timerId);
                    ddTitle('cleanDjsTimer : ' . $res . ' | id : ' . $timerId);
                }
            }
            //再执行注册
            $addtask = $redis->rpop($addkey);    //rPop
            if ($addtask) {
                $timerArr = json_decode($addtask, true);
                $wait_time = $timerArr['wait_time'] * 1000;
                $account = $timerArr['account'];
                $timerId = \Swoole\Timer::after((int)$wait_time, function () use ($account) {
                    $playerInfo = Djs::getDjsPlayerData($account);
                    $playerInfo['status'] = 0;
                    $playerInfo['timer'] = 0;
                    Djs::updatePlayerData($account, $playerInfo);
                });
                $playerInfo = Djs::getDjsPlayerData($account);
                $playerInfo['timer'] = $timerId;
                Djs::updatePlayerData($account, $playerInfo);
            }
        }
    }
}
